<?php

namespace app\app\controller;

use think\Db;
use think\Validate;
use think\File;
use cmf\controller\RestBaseController;
use rongyun\API\RongCloud;

class OthersController extends RestBaseController{

	 /**
     * Token 换用户ID
     * @param token 用户token
     */
    public function tokenToUserId($validate_rule,$validate_rule_msg,$info){
        //验证必要参数是否存在
		$validate=new Validate($validate_rule);

		$validate->message($validate_rule_msg);

		if (!$validate->check($info)) {
			exit(json_encode(array(
				'code'=>'error',
				'msg'=>$validate->getError(),
			)));
		}

		//查看是否登录
		$get_user_and_token=Db::name('user u,nc_user_token ut')->field('u.id,u.mobile,u.unionid,u.screen_name,u.user_nickname,u.balance,u.user_type,u.avatar')->where('u.id=ut.user_id')->where(['ut.token'=>$info['token']])->find();

		if($get_user_and_token && (isset($get_user_and_token['mobile']) || isset($get_user_and_token['unionid']) || isset($get_user_and_token['screen_name']) || isset($get_user_and_token['id']))){

		}else{
			exit(json_encode(array(
				'code'=>'error',
				'msg'=>'token失效，请重新登录',
				'status'=>0
			)));
		}
		return $get_user_and_token;
    }

    //获取Token
    public function token($u_id,$u_nickname,$u_avatar){
        require_once EXTEND_PATH."rongyun/API/rongcloud.php";
        $appKey = '***********';
        $appSecret='***********';

        $p = new RongCloud($appKey,$appSecret);

        $id = $u_id;
        $nickname = $u_nickname;
        $avatar = $u_avatar;

        $token = $p->User()->getToken($id, $nickname, $avatar);
        return $token;
    }

    //token换rongyuntoken
    public function tokenToRongyuntoken(){
    	Db::startTrans();
	
		try{ // 提交事务

			$info = $this->request->param();

			//参数规则
		    $validate_rule=[
	    		'token' => 'require|length:30',
			];

			$validate_rule_msg=[
				'token.require'=>'没有token令牌！',
				'token.length'=>'token令牌位数错误！',
			];

			//安全校验 成功则返回该用户信息
			$get_user_and_token=$this->tokenToUserId($validate_rule,$validate_rule_msg,$info);

			if($get_user_and_token){
				//根据返回的用户信息（用户ID，昵称，头像） 获取rongyuntoken
	            $token = $this->token($get_user_and_token['id'],$get_user_and_token['user_nickname'],cmf_get_image_url($get_user_and_token['avatar']));
	            $data['token'] = json_decode($token)->token;
			}

			Db::commit();
		} catch (\Exception $e) {
		    // 回滚事务
		    Db::rollback();
		    exit(json_encode(array(
				'code'=>'error',
				'msg'=>'出错了:'.($e),
			)));
		}

		$ret['code'] = 'success';
		$ret['msg'] = '获取用户信息成功';
		$ret['data'] = $data;
		echo json_encode($ret);exit;
    }

	 /**
     * 获取聊天对象的 用户ID、头像和昵称
     */
    public function getUserInfo(){
    	Db::startTrans();
	
		try{ // 提交事务

			$info = $this->request->param();

			//参数规则
		    $validate_rule=[
	    		'token' => 'require|length:30',
			];

			$validate_rule_msg=[
				'token.require'=>'没有token令牌！',
				'token.length'=>'token令牌位数错误！',
			];
			//安全校验 成功则返回该用户信息
			$get_user_and_token=$this->tokenToUserId($validate_rule,$validate_rule_msg,$info);

			if($get_user_and_token){

				//获取对方的（商家/客服……） ID、头像、昵称
	            // $token = $this->token($info['user_id'],$info['nickname'],$info['avatar']);
				// $data['token'] = json_decode($token)->token;

				$data['user_id'] = $info['user_id'];
				$data['nickname'] = $info['nickname'];
				$data['avatar'] = $info['avatar'];
	            
			}

			Db::commit();
		} catch (\Exception $e) {
		    // 回滚事务
		    Db::rollback();
		    exit(json_encode(array(
				'code'=>'error',
				'msg'=>'出错了:'.($e),
			)));
		}

		$ret['code'] = 'success';
		$ret['msg'] = '获取用户信息成功';
		$ret['data'] = $data;
		echo json_encode($ret);exit;
    }
}
 